<?php
/**
 * Note: 游戏相关  数据加密之类
 */
namespace App\Services;

use Illuminate\Support\Facades\Http;

class GameService
{
    protected static $configs = [];

    /**
     * @param null $key
     * @return array|\Illuminate\Config\Repository|\Illuminate\Contracts\Foundation\Application|mixed|null
     */
    protected static function getConfig($key = null)
    {
        if (!self::$configs) self::$configs = config('game');

        return $key ? (self::$configs[$key] ?? null) : self::$configs;
    }

    /**
     * 加密 IV就是key的前16位
     * @param string $data
     * @param string $key
     * @return string
     */
    public static function encrypt(string $data, string $key = ''): string
    {
        if (empty($key)) $key = self::getConfig('aes_key');
        $iv = substr($key, 0, 16);
        $ciphertext = openssl_encrypt($data, "aes-256-cbc", $key, 1, $iv);
        return base64_encode($ciphertext);
    }

    /**
     * 解密 IV就是key的前16位
     * @param string $data
     * @param string $key
     * @return false|string
     */
    public static function decrypt(string $data, string $key = '')
    {
        if (empty($key)) $key = self::getConfig('aes_key');
        $iv = substr($key, 0, 16);
        $ciphertext = base64_decode($data);
        return openssl_decrypt($ciphertext, "aes-256-cbc", $key, 1, $iv);
    }

    /**
     * @param int $port
     * @param string $url
     * @param array $data
     * @return \GuzzleHttp\Promise\PromiseInterface|\Illuminate\Http\Client\Response
     * @throws \Exception
     */
    public static function requestPost(int $port, string $url, array $data = [])
    {
        $serverIp = collect(config('game.withdraw_white_ip'))->random(1)->first();
        $url = "http://{$serverIp}:{$port}{$url}";
        try {
            info(__METHOD__, [$url, $data]);
            $response = Http::timeout(5)->asJson()->post($url, $data);
            $response->throw();
            info(__METHOD__, [$response]);
        } catch (\Exception $e) {
            report($e);
            throw new \Exception("操作失败，请稍候再试");
        }
        return $response;
    }
}
